'use strict'
const compose = require('koa-compose')
const router = require('koa-router')()
/* 用户模块 */
const userLoginRouter = require('./user/login').routes()
const userRegisterRouter = require('./user/register').routes()
const userUpdateRouter = require('./user/update').routes()

/* 文章模块 */
const addArticleRouter = require('./article/add').routes()
const deleteArticleRouter = require('./article/delete').routes()
const updateArticleRouter = require('./article/update').routes()
const articleListRouter = require('./article/list').routes()

// 首页
const index = router.get('/', ctx => {
  ctx.type = 'text/html;charset=utf-8'
  ctx.body = `
      <h2 style="display: flex;
        justify-content: center;
        align-items: center;
        height: calc(100vh - 40px);">
        Welcome To Angular System
      </h2>`
}).routes()

const errorLog = async(ctx, next) => {
  try {
    await next()
  } catch (err) {
    ctx.response.status = err.statusCode || err.status || 500
    ctx.response.body = {
      code: 0,
      message: err.msg,
      data: []
    }
    // 手动释放error事件
    ctx.app.emit('error', err, ctx)
  }
}

/*
* 日志输出
* */
const errorConsole = ctx => {
  console.log(`\r============================= Error log: =============================
              method  ==> ${ctx.request.method} 
              url  ==> ${ctx.request.url}
              msg  ==> ${JSON.stringify(ctx.request.body || ctx.query)}
              \r============================= Error end =============================`)
}

const middlewares = compose(
  [
   /* 用户模块 */
    userLoginRouter,
    userRegisterRouter,
    userUpdateRouter,
    addArticleRouter,
    deleteArticleRouter,
    updateArticleRouter,
    articleListRouter,
    index,
    errorLog,
    errorConsole
  ])

module.exports = middlewares
